/*
 * 全局权限检测
 * 包括1、路由的全局守卫
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'// progress bar style
import { getToken,clearTokenAndStore } from '@/common/auth'
import Vue from 'vue'
import de from 'element-ui/src/locale/lang/de'
NProgress.configure({ showSpinner: false })
let instance=new Vue();
// 路由全局前置守卫
const whiteList = ['/login','/404']  // 白名单
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  console.log('当前去往的路由需要的权限是:'+to.meta.permissionCode)
  if (whiteList.includes(to.path)) { // 白名单，免密登录
    NProgress.done();
    if (to.path==='/login'){
      clearTokenAndStore();
    }
    next()
  } else { // 否则就跳动登录页面
    if (getToken()) {
      // 有token，没有permissions
      if (instance.isNullOrEmpty(store.getters.permissions)) {
        NProgress.done();
         store.dispatch('refreshUserByToken').then(resp => {
          store.dispatch('filterAuthRouters', { permissionCode:resp.permissionCode }).then(() => {
            next({
              ...to,
              replace: true
            })
          })
        }).catch((e) => {
          store.dispatch('logout').then(() => {
            next('/login')
          }).catch(()=>{
            clearTokenAndStore();
            next('/login')
          })
        })
      } else {
        next()
      }

    }else{
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
